package com.hxk.juc.thread.prodCons;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用ReentrantLock实现生产者和消费者案例
 *
 */
public class ReentrantLockProdConsCase {
    public static void main(String[] args) {
        LockData lockData = new LockData();

        for (int i = 1; i <= 5; i++) {
            new Thread(()->{lockData.prodM();},String.valueOf(i)).start();
        }

        for (int i = 1; i <= 5; i++) {
            new Thread(()->{lockData.consM();},String.valueOf(i)).start();
        }
    }
}

class LockData{

    //库存
    private volatile int num = 0;
    private Lock lock = new ReentrantLock();
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();

    /**
     * 生产者
     */
    public void prodM(){
        lock.lock();
        try{
            //库存判断
            while (num != 0){
                c1.await();
            }
            //开始生产
            num++;
            System.out.println(Thread.currentThread().getName()+"\t 生产："+num);
            //通知消费者消费
            c2.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    /**
     * 消费者
     */
    public void consM(){
        lock.lock();
        try{
            //判断库存
            while (num == 0){
                c2.await();
            }
            //消费
            num--;
            System.out.println(Thread.currentThread().getName()+"\t 消费："+num);
            //通知生产者生产
            c1.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
